<template>
  <div>
    <van-cell-group>
      <van-cell title="订单号" :value='tradeData.tradeNo'/>
      <van-cell title="ICCID号" :value='tradeData.iccid'/>
      <van-cell title="套餐名称" :value='tradeData.pkgName'/>
      <van-cell title="套餐流量" :value='`${tradeData.flow}MB`'/>
      <van-cell title="套餐有效期" :value='tradeData.pkgKind!==3?date:currentMonthLast'/>
      <van-cell title="套餐价格" :value='`${tradeData.amount}元`' />
    </van-cell-group>
    <div style="margin:40px 0;padding: 0 20px">
      <van-button type="primary" style="width: 100%" @click="submit">微信支付</van-button>
      <van-button type='warning' style="width: 100%;margin-top: 20px;" @click="()=>{showInfo=true}">余额支付</van-button>
    </div>
    <van-dialog
      v-model="showInfo"
      title=""
      @confirm="recharge"
      confirmButtonText="确认支付"
      confirmButtonColor='#1989fa'
      showCancelButton>
      <div class="dialog-content">
        <div>当前卡余额：{{balance}} 元</div>
        <div>订单金额：{{tradeData.amount}} 元</div>
        <div>支付后余额：{{(balance*100-tradeData.amount*100)/100}} 元</div>
      </div>
    </van-dialog>


  </div>
</template>

<script>
  import {getCurrentMonthLast, inCreaseMonth, urlSearch} from "../../utils";
  import {getRecharge, getTradeDetail, notifyTrade, pay, recharge} from "../../api/user";
  import wx from 'weixin-js-sdk'
  import {Toast} from "vant";

  export default {
    name: "confirm",
    data(){
      return{
        tradeData:{},
        date:'',
        currentMonthLast:getCurrentMonthLast(),
        showInfo:false,
        balance:0
      }
    },
    beforeMount() {
      const Url = window.location.href
      let newUrl = ''
      if(Url.includes('/#/')){
        localStorage.setItem('tradeId',urlSearch('id'))
        newUrl = Url.replace('#','?#')
        location.replace(newUrl)
      }
    },
    // beforeRouteLeave(){
    //   console.log( location.href)
    //
    // },
    mounted() {
      this.getDetail()
    },
    methods: {
      async getDetail(){
        const res = await getTradeDetail(localStorage.getItem('tradeId'))
        const pkgCycleMap = new Map([
          [1,1],[2,3],[3,12]
        ])
        this.date ="截止"+inCreaseMonth(pkgCycleMap.get(res.data.pkgCycle),res.data.createTime)
        if(res.data.pkgKind === 2){
          this.date='有效期与当前主套餐一致'
        }
        this.tradeData=res.data
        this.getRecharge(this.tradeData.msisdn)
      },
      // 查询余额
      getRecharge(msisdn){
        // 查询余额
        getRecharge(msisdn).then(res=>{
          this.balance = res.data.balance||0
        })
      },
      // 余额支付
      async recharge(tradeId){
        try {
          await recharge(localStorage.getItem('tradeId'))
          Toast.success('支付成功');
          setTimeout(()=>{
            location.href = '/wexin/#/home'
          },1000)

        }catch (e) {
          Toast(e.errParams[0]);
        }


      },
      async submit() {
        // todo 跳到微信支付页
        const {clientIp,h5Type} = this.tradeData
        const reqData = {
          clientIp,
          h5Type,
          tradeId:this.tradeData.id
        }
        try {
          const res = await pay(reqData)
          const payData = JSON.parse(res.data)
          console.log(payData)
          const {appId,timeStamp,nonceStr,signType,paySign} = payData
          const preId = payData.package
          console.log(appId)
          const _this = this
          wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: appId, // 必填，公众号的唯一标识
            jsApiList: ['chooseWXPay'], // 必填，需要使用的JS接口列表
          });
          wx.ready(function(){
            wx.chooseWXPay({
              appId:appId,
              timestamp: timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
              nonceStr: nonceStr, // 支付签名随机串，不长于 32 位
              package: preId, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
              signType: signType, // 微信支付V3的传入RSA,微信支付V2的传入格式与V2统一下单的签名格式保持一致
              paySign: paySign, // 支付签名
              success: async function (res) {
                // 支付成功后的回调函数
                await notifyTrade(localStorage.getItem('tradeId'))
                location.href = '/wexin/#/home'
              }
            });
          });

        }
        catch (e) {
          Toast(e.errParams[0]);
        }
      }
    }
  }
</script>

<style scoped>
  .van-cell__title{
    flex: 0.3;
  }
  .dialog-content{
    margin:20px 20px;
    color: #666;
  }
</style>
